﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MicropleSoft.WmsServiceLibrary.BusinessInterfaces;
using MicropleSoft.WmsServiceLibrary.Domain;
using MicropleSoft.WmsServiceLibrary.Exceptions;
using MicropleSoft.WmsServiceLibrary.Models;
using MicropleSoft.WmsServiceLibrary.ServiceFactory;

namespace MicropleSoft.WmsService.PurchaseOrder
{
    public class PurchaseOrderLogic :WmsServiceLibrary.SqlServer.Base.BaseServiceSqlServer, IPurchaseOrderLogic
    {
        private readonly AbstractServiceFactory _abstractServiceFactory = ServiceFactoryCreator.CreateAbstractServiceFactory();
        public void Save(PurchaseOrderWrap purchaseOrderWrap)
        {
            _abstractServiceFactory.CreatePurchaseOrderService().Save
                (purchaseOrderWrap.PPurchaseOrder,
                 purchaseOrderWrap.PPurchaseOrderDetails.ToList<IPurchaseOrderDetail>());
            
        }

        public PurchaseOrderWrap GetPurchaseOrderWrapByPo(string poId, string whId)
        {
            var  purchaseOrderWrap = new PurchaseOrderWrap();
            string condition = " and PO_ID = '{0}' and WH_ID = '{1}'";
            condition = string.Format(condition, poId, whId);
            var purchaseOrder = _abstractServiceFactory.CreatePurchaseOrderService().Query(condition);
            if(purchaseOrder == null || purchaseOrder.Count ==0 )
            {
                const string exceptionMsg = "仓库{0}不存在采购订单对象：{1}";
                throw new AppServerException(string.Format(exceptionMsg,whId,poId));
            }
            purchaseOrderWrap.PPurchaseOrder = purchaseOrder[0];
            purchaseOrderWrap.PPurchaseOrderDetails = _abstractServiceFactory.CreatePurchaseOrderDetailService().Query(condition);
            return purchaseOrderWrap;
        }
    }
}
